<?php



/**
 * Api服务类
 * author: 爱是西瓜
 * DateTime: 2018/5/10 22:19
 */
class Api{

    public static $getTokenInfo = 'http://tpshop.mbku.net/home/api/getTokenInfo.html';

    /**
     * 服务启动初始化方法
     */
    public static function start(){

        //初始化
        Db::update(['end_time'=>time()],'ws_service_log',"WHERE end_time=0");

    }

    /**
     * 链接关闭处理方法
     * @param $ws
     * @param $ws_uid
     */
    public static function close($ws,$ws_uid){

        echo '上次连接：'.$ws_uid.PHP_EOL;

        //获取断开连接的用户信息
        $myUser = Cache::getCliUser($ws_uid);

        var_dump($myUser);

        //用户
        if($myUser['type'] == 'userInit'){

            $userCli = Db::find('ws_service_log',"where end_time=0 and client_id='{$ws_uid}'",'kf_id');
            $kf = Cache::getUidKf('KF'.$userCli['kf_id']);
            var_dump($kf);
            $ws->push($kf['client_id'], myResult('delUser', ['id' => $myUser['uid']]));
        }

        //客服
        if($myUser['type'] == 'init'){

            $kf_id = substr($myUser['uid'],2);
            Db::update(['online'=>2],'ws_users',"WHERE id='{$kf_id}'");

            Cache::setUidKf($myUser['uid'],null);
        }

        //将全局用户数组（连接id）中删除断开连接的用户
        Cache::setCliUser($ws_uid,null);

    }


    /**
     * 客服初始链接
     * @param $data
     * @param $ws
     * @param $request
     */
    public static function init($data,$ws,$request){

        //将连接信息存放到fd的全局数组中( $request->fd 为连接id )
        $data = array_merge($data,Cache::getCliUser($request->fd));
        Cache::setCliUser($request->fd,$data);

        echo '客服：'.json_encode($data).PHP_EOL;

        $kf_id = substr($data['uid'],2);

        Db::update(['online'=>1],'ws_users',"WHERE id='{$kf_id}'");

        //分配客服
        $kf = ['id'=>$kf_id,'user_name'=>$data['name']];
        $log = ApiModel::dataToDb($data,$kf);
        Cache::setUidKf($log['user_id'],$log);

    }

    /**
     * 用户初始链接
     * @param $data
     * @param $ws
     * @param $request
     * @return bool
     */
    public static function userInit($data,$ws,$request){

        //将连接信息存放到fd的全局数组中( $request->fd 为连接id )
        $data = array_merge($data,Cache::getCliUser($request->fd));

        $tokenInfo = curl_get(self::$getTokenInfo,['mytoken'=>$data['mytoken']]);
        $tokenInfo = json_decode($tokenInfo,true);
        if($tokenInfo['code'] != 200){
            //分配链接客服信息
            $ws->push($request->fd,myResult('wait',['content'=>'获取用户信息失败~']));
            return false;
        }

        $user  = $tokenInfo['data']['user'];
        echo json_encode($user).PHP_EOL;
        var_dump($tokenInfo['data']);
        $data['data'] = base64_encode(json_encode($tokenInfo['data']));
        $data['uid'] = $user['user_id'];
        $data['name'] = $user['nickname'];
        $data['avatar'] = $user['avatar'];

        echo PHP_EOL;
        echo $data['data'].PHP_EOL;

        //根据组与用户编号获取分配的客服信息
        $kf = ApiModel::getkf($data['group'],$data['uid']);
        if(empty($kf) || $kf['online']!=1){
            //分配链接客服信息
            $ws->push($request->fd,myResult('wait',['content'=>'暂无客服接待，稍后再来~']));
            return false;
        }



        //写入ws_service_log
        $log = ApiModel::dataToDb($data,$kf);

        Db::add($log,'ws_service_log');

        Cache::setCliUser($request->fd,$data);

        //分配链接客服信息
        $ws->push($request->fd,myResult('connect',["kf_id"=>"KF{$kf['id']}","kf_name"=>$kf['user_name']]));

        //客服分配用户信息
        $kf_user = Cache::getUidKf('KF'.$kf['id']);

        $kf_msg = ['id'=>$data['uid'],'name'=>$data['name'],'avatar'=>$data['avatar'],'data'=>$tokenInfo['data'],'ip'=>$data['ip'],'group'=>$data['group'],'client_id'=>$data['id']];
        $ws->push($kf_user['client_id'],myResult('connect',["user_info"=>$kf_msg]));

    }

    /**
     * 客户端提交信息处理（用户与客服）
     * @param $data
     * @param $ws
     * @param $request
     */
    public static function chatMessage($data,$ws,$request){

        $userInfo = Cache::getCliUser($request->fd);
        var_dump('测试：');
        var_dump($userInfo);

        $addData = $data['data'];
        $addData['from_id'] = $userInfo['uid'];
        $addData['from_name'] = $userInfo['name'];
        $addData['from_avatar'] = $userInfo['avatar'];
        $addData['time_line'] = time();
        $rs = Db::add($addData,'ws_chat_log');

        //发送给用户
        if($addData['to_id'] && $rs){

            //获取用户当前连接列表
            $link_list = ApiModel::getUidLinks($addData['to_id']);
            foreach ($link_list as $k=>$link){
                $msg = [ 'id'=>$addData['from_id'],'name'=>$addData['from_name'],'avatar'=>$addData['from_avatar'],'content'=>$addData['content'],'time'=>date('i:s') ];
                $ws->push($link['client_id'],myResult('chatMessage',$msg));
            }
            unset($link_list);
        }



    }

    /**
     * 切换客服组
     * @param $data
     * @param $ws
     * @param $request
     */
    public static function changeGroup($data,$ws,$request){

        //分配客服
        $kf = ['id'=>7,'user_name'=>'ztlong2'];

        Db::update(['group_id'=>$data['group'],'kf_id'=>$kf['id']],'ws_service_log',"WHERE user_id ='{$data['uid']}'");

        //推送给客服
        $kf_user = Cache::getUidKf('KF'.$kf['id']);

        //根据用户获取当前链接列表
        $link_list = ApiModel::getUidLinks($data['uid']);
        foreach ($link_list as $k=>$link){
            $kf_msg = ['id'=>$data['uid'],'name'=>$data['name'],'avatar'=>$data['avatar'],'ip'=>$data['ip'],'group'=>$data['group'],'client_id'=>$link['id']];
            $ws->push($kf_user['client_id'],myResult('connect',["user_info"=>$kf_msg]));
        }
        unset($link_list);

    }


}